<?php
class Admin_AjaxController extends Zend_Controller_Action
{
    protected $_user;
    protected $_category;
    protected $_roles;
    protected $_content;

    public function init() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $this->_user     = Zend_Auth::getInstance()->getIdentity();
        $this->_category = new Admin_Model_Category();
        $this->_roles    = new Admin_Model_Roles();
        $this->_content  = new Admin_Model_Content();
    }

    public function imageUploadAction() {
        $post = $this->getRequest()->getPost();

        $adapter = new Zend_File_Transfer_Adapter_Http();                
        $file    = $adapter->getFileInfo();        
        $key     = isset($file['file'])?'file':'files_0_';        

        if (!$post) {
            $folderName = $this->_getParam('folder');
        } else {
            $folderName = isset($post['folder_name'])?$post['folder_name']
                                                 :$post['image_folders_multiupload'];
        }               

        if ($folderName != '.') 
            $folderName = '/' . $folderName . '/';       
        else
            $folderName = '/';    
        
        $image   = new My_Images($file[$key]);        

        $adapter->addValidator('Extension', 
                               false, 
                               array(
                                   'extension' => 'jpg,gif,jpeg,png', 
                                   'case'      => false));
        $adapter->setDestination('public/uploads/images' . $folderName);                                 

        $fileProperties = new stdClass();
        $fileProperties->name = $this->_user->role.'_'.uniqid().'.'.$image->getImageExtension();        
        $fileProperties->size = $file[$key]['size'];        
        $adapter->addFilter('Rename', $fileProperties->name);


        if ($adapter->isUploaded($file[$key]['name']) 
            && $adapter->isValid($file[$key]['name'])) {
            
            if ($adapter->receive($file[$key]['name'])) {                
                $uploadedImage = 'public/uploads/images' . $folderName . $fileProperties->name;
                //if the size of image more than 200kb - reduce the size
                if ($image->sizeMoreThan(200)) {                    
                    $image->compressImage($uploadedImage, 70);                    
                    $fileProperties->size = filesize($uploadedImage);                    
                }                
                $fileProperties->url = '/' . $uploadedImage;
                $response = array(
                    'filelink' => '/public/uploads/images' . $folderName . $fileProperties->name,
                    'files'    => array($fileProperties)
                );
                echo Zend_Json::encode($response);
                return;
            } else {
                $fileProperties->name = 'Error: something was wrong, try again';
                $fileProperties->size = 0;                
            }          
        } else {
            $fileProperties->name = 'Error: bad image format';
            $fileProperties->size = 0;
        }       
        $response = array(
            'files' => array($fileProperties)
        );
        echo Zend_Json::encode($response);
    }

    public function imageFoldersAction() {
        $path = 'public/uploads/images';
        $dirs = array();
        $entries = scandir($path);        
        foreach ($entries as $entry) {
            if ($entry == '.' || $entry == '..') continue;
            if (is_dir($path . '/' . $entry)) {                
                $dirs[] = $entry;
            }
        }
        echo Zend_Json::encode($dirs);
    }

    public function uploadedImagesAction() {
        $folder = $this->_getParam('folder');
        if (!$folder)
            $folder = '';

        $path = 'public/uploads/images' . '/' . $folder;        
        function getDirImages($path) {        
            $images = array();
            $folders = array();
            $separator = substr($path, -1)=='/'?'':'/';                        
            $dirEntries = scandir($path);                                    
            foreach ($dirEntries as $entry) {
                if ($entry == '.' || $entry == '..') continue;
                if (is_dir($path . $separator . $entry)) {                                          
                    $folders[] = $entry;                
                } else {                    
                    $separator = substr($path, -1)=='/'?'':'/';                    
                    $images[] = array(
                        'image'  => '/' . $path . $separator . $entry,
                        'thumb'  => '/' . $path . $separator . $entry                        
                    );
                }
            }
            return array(
                'images'  => $images,
                'folders' => $folders
            );                        
        }            
        $response = getDirImages($path);        
        echo Zend_Json::encode($response);        
    }

    public function createFolderAction() {
        $folderName = $this->getRequest()->getPost('folder_name');
        $folderName = ltrim(rtrim($folderName));
        $response   = array();
        $path       = 'public/uploads/images';        

        if (empty($folderName) || !preg_match('/[a-zA-Z0-9]+/', $folderName)) {
            $response['result']  = 'error';
            $response['message'] = 'bad folder name';
        }        

        $folderName = str_replace('/', '_', $folderName);
        $folderName = str_replace(' ', '_', $folderName);
        
        if (!isset($response['result'])) {
            if (file_exists($path . '/' . $folderName)) {
                $response['result']  = 'error';
                $response['message'] = 'folder already exists';
            } else {
                if (mkdir($path . '/' . $folderName)) {
                    $response['result']      = 'success';
                    $response['message']     = 'folder successfully created';
                    $response['folder_name'] = $folderName;
                } else {
                    $response['result']  = 'error';
                    $response['message'] = 'something was wrong, please try again';
                }
            }            
        }
        echo Zend_Json::encode($response);
    }

    public function changeCategoryPositionAction() {        
        $post     = $this->getRequest()->getPost();
        $response = array();        
        try {
            $this->_category->updateCategoriesPosition($post['data']);
            $response['result'] = 'success';
        } catch(Exception $e) {
            $response['result'] = 'fail';
        }
        My_Cache::clearCache('menu');
        My_Cache::cleanTagCache(array('dept_menu'));
        echo Zend_Json::encode($response);
    }

    public function getCategoriesAction() {
        $post         = $this->getRequest()->getPost();
        $departmentId = $post['department_id'];
        $categoryId   = $post['category_id']?$post['category_id']:false;

        $categories = $this->_category->getAvailableForRoleCategoriesByDepartmentId(
            $this->_user->roleId, 
            $departmentId
        );

        if ($categoryId != 'null') {
            $parentCategory = $this->_category->getParentCategoryBySubCategoryId($categoryId);
            //if parent category already allowed for user, 
            //then this category already exist in an array
            $parentCategoryAllowed = false;
            foreach ($categories as $key => $category) {
                if ($parentCategory['id'] == $category['id']) $parentCategoryAllowed = true;                
                if (!$this->_category->canBeParentFor($categoryId, $category['id'])) {
                    unset($categories[$key]);                    
                }                
            }            
            if (!$parentCategoryAllowed) $categories[] = $parentCategory;            
        }        
        echo Zend_Json::encode($categories);        
    }

    public function getAllCategoriesAction() {
        $post           = $this->getRequest()->getPost();
        $departmentId   = $post['department_id'];
        $roleCategories = $post['role_categories'];
        echo Zend_Json::encode($this->_category->getCategoriesByDepartmentId( 
            $departmentId,
            $roleCategories
        ));           
    }

    public function saveRoleAction() {
        $post = $this->getRequest()->getPost('data');

        $roleName = ltrim(rtrim($post['role_name']));
        if (!$roleName) {
            echo Zend_Json::encode(array('message' => 'Bad role name'));
            return;
        }        

        if ($this->_roles->roleIsExists($roleName)) {
            echo Zend_Json::encode(array('message' => 'Role already exists'));
            return;
        }

        $roleId = $this->_roles->saveRole($roleName);
        
        if (isset($post['categories'])) {
            $categoriesData = array();
            foreach ($post['categories'] as $category) {                
                $categoriesData['role_id']     = $roleId;
                $categoriesData['category_id'] = $category;                
                $this->_roles->saveRoleCategories($categoriesData);
            }
        }

        if (isset($post['types'])) {
            $categoryTypesData = array();
            foreach ($post['types'] as $categoryTypeId) {                
                $categoryTypesData['role_id']          = $roleId;
                $categoryTypesData['category_type_id'] = $categoryTypeId;                
                $this->_roles->saveRoleCategoryTypes($categoryTypesData);
            }
        }

        if (isset($post['departments'])) {
            $departmentsData = array();
            foreach ($post['departments'] as $departmentId) {                
                $departmentsData['role_id']       = $roleId;
                $departmentsData['department_id'] = $departmentId;                
                $this->_roles->saveRoleDepartments($departmentsData);
            }
        }

        if (isset($post['resources'])) {
            $resourcesData = array();
            foreach ($post['resources'] as $resourceId) {                
                $resourcesData['role_id']     = $roleId;
                $resourcesData['resource_id'] = $resourceId;                
                $this->_roles->saveRoleResources($resourcesData);
            }
        }

        My_Cache::clearCache('acl');
        echo Zend_Json::encode(array('message' => 'role was created'));
    }

    public function editRoleAction() {
        $post   = $this->getRequest()->getPost('data');
        $roleId = $this->getRequest()->getPost('role_id');

        $roleName = ltrim(rtrim($post['role_name']));
        if (!$roleName) {
            echo Zend_Json::encode(array('message' => 'Bad role name'));
            return;
        }        

        $this->_roles->updateRole($roleName, $roleId);
        $this->_roles->deleteRoleCategories($roleId);
        $this->_roles->deleteRoleCategoryTypes($roleId);
        $this->_roles->deleteRoleDepartments($roleId);
        $this->_roles->deleteRoleResources($roleId);
        
        if (isset($post['categories'])) {
            $categoriesData = array();
            foreach ($post['categories'] as $category) {                
                $categoriesData['role_id']     = $roleId;
                $categoriesData['category_id'] = $category;                
                $this->_roles->saveRoleCategories($categoriesData);
            }
        }

        if (isset($post['types'])) {
            $categoryTypesData = array();
            foreach ($post['types'] as $categoryTypeId) {                
                $categoryTypesData['role_id']          = $roleId;
                $categoryTypesData['category_type_id'] = $categoryTypeId;                
                $this->_roles->saveRoleCategoryTypes($categoryTypesData);
            }
        }

        if (isset($post['departments'])) {
            $departmentsData = array();
            foreach ($post['departments'] as $departmentId) {                
                $departmentsData['role_id']       = $roleId;
                $departmentsData['department_id'] = $departmentId;                
                $this->_roles->saveRoleDepartments($departmentsData);
            }
        }

        if (isset($post['resources'])) {
            $resourcesData = array();
            foreach ($post['resources'] as $resourceId) {                
                $resourcesData['role_id']     = $roleId;
                $resourcesData['resource_id'] = $resourceId;                
                $this->_roles->saveRoleResources($resourcesData);
            }
        }

        My_Cache::clearCache('acl');
        echo Zend_Json::encode(array('message' => 'role was edited'));
    }

    public function checkCategoryAction() {
        $categoryId = $this->getRequest()->getPost('category_id');

        $response           = array();
        $response['result'] = 'success';

        $postData   = $this->_content->getPostByCategoryId($categoryId);
        //hack for news categories
        if ($postData && $postData['type_id'] != 2) {
            $response['result']  = 'error';
            $response['message'] = 'У выбранной категории уже есть материал: ' . $postData['title'];            
            $response['post_id'] = $postData['id'];
        } else {
            $categoryData = $this->_category->getCategoryData($categoryId);
            $result = $this->_category->checkCategoryType($categoryData['type_id']);
            if (!$result) {
                $response['result']  = 'error';
                $response['message'] = 'Тип выбранной категории не позволяет создавать в ней материал';
            }
        }        
        echo Zend_Json::encode($response);
    }

    public function checkParentCategoryTypeAction() {
        $categoryId = $this->getRequest()->getPost('category_id');

        $response = array('result' => 'success');

        if ($categoryId != 0) {
            $categoryData = $this->_category->getCategoryData($categoryId);
            $result = $this->_category->checkCategoryType($categoryData['type_id'], false);
            if (!$result) {
                $response['result']  = 'error';
                $response['message'] = 'Тип выбранной категории не позволяет ей иметь дочернюю категорию';
            }
        }        
        echo Zend_Json::encode($response);
    }

    public function fileUploadAction() {  
        $adapter = new Zend_File_Transfer_Adapter_Http();                
        $file    = $adapter->getFileInfo();
        $adapter->setDestination('public/uploads/files/');
        $response = array(
            'response' => 'something was wrong, please try again!'
        );
        $ext = pathinfo($file['file']['name'], PATHINFO_EXTENSION);
        $newName = md5(uniqid(rand(), true)) . '.' . $ext;
        $adapter->addFilter('Rename', $newName);
        if ($adapter->isUploaded($file['file']['name']) 
            && $adapter->isValid($file['file']['name'])) {
            
            if ($adapter->receive($file['file']['name'])) {
                $response = array(
                    'filelink' => '/public/uploads/files/'.$newName,
                    'filename' => $file['file']['name']
                );                            
            }        
        }
        echo Zend_Json::encode($response);
        //var_dump($adapter);
        //var_dump($file);
        /*$response = array(
            'filelink' => '/files/'.$_FILES['file']['name'],
            'filename' => $_FILES['file']['name']
        );*/
    }
}